<template>
  <el-dialog
    :model-value="props.visible"
    title="设置用户角色对话框"
    width="90%"
    :lock-scroll="false"
    :close-on-click-modal="false"
    :before-close="closeDialog"
    @open="openDialogHandler"
  >
    <div style="min-height: 50vh">
      <TableCard operation-bar-label="批量管理用户角色">
        <template #operationBar>
          <el-popconfirm
            title="确认批量删除用户角色？"
            placement="right"
            @confirm="
              setUserRoles(UserDataSetTypeEnum.REMOVE, multipleDeleteItems)
            "
          >
            <template #reference>
              <el-button v-once-click color="#F56C6C" plain size="small">
                批量删除角色
              </el-button>
            </template>
          </el-popconfirm>

          <div class="label">
            当前设置用户： {{ userName }} - @{{ userAccount }}
          </div>
        </template>

        <template #table>
          <el-table
            :data="userRoleList"
            stripe
            size="small"
            style="width: 100%"
            max-height="200"
            @selection-change="deleteItemSelectionChange"
            :headerCellStyle="tableHeaderCellStyle"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column property="enable" label="enable" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.enable === 1" type="danger">
                  禁用
                </el-tag>
                <el-tag v-if="scope.row.enable === 0" type="success">
                  启用
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column property="name" label="Name" sortable width="160">
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <div style="margin-right: 6px">{{ scope.row.name }}</div>
                  <el-icon
                    v-if="scope.row.isDefault == 0"
                    title="默认用户角色"
                    color="#eebe77"
                    size="17"
                  >
                    <InfoFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="realName" label="RealName" width="160" />
            <el-table-column label="Sort" min-width="400">
              <template #default="scope">
                {{
                  getDescriptionStr(
                    findParentValues(sortTree, scope.row?.sortId)
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column label="operation" width="100" fixed="right">
              <template #default="scope">
                <el-popconfirm
                  title="确认删除用户角色？"
                  placement="right"
                  @confirm="
                    setUserRoles(UserDataSetTypeEnum.REMOVE, [scope.row.id])
                  "
                >
                  <template #reference>
                    <el-button
                      v-if="scope.row.isDefault != 0"
                      v-once-click
                      color="#F56C6C"
                      plain
                      size="small"
                    >
                      删除角色
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </TableCard>

      <br />

      <TableCard operation-bar-label="批量设置用户角色">
        <template #topBar>
          <div class="inputForm">
            <div class="inputItem">
              <div class="label">条件查询角色</div>
              <div class="value">
                <el-cascader
                  v-model="queryRoleSortId"
                  :options="sortTypeTree"
                  :props="{ checkStrictly: true }"
                  placeholder="请选择上级分类（可选）"
                  clearable
                  @visible-change="selectVisibleChangeHandler"
                  size="large"
                  style="width: 100%"
                />
              </div>
            </div>
            <!-- <div class="inputItem" style="width: 300px">
              <div class="label">角色名称</div>
              <div class="value">
                <el-input
                  v-model="queryRoleName"
                  style="width: 100%; height: 100%"
                  clearable
                  placeholder="角色名称"
                />
              </div>
            </div> -->

            <div class="buttonItem">
              <div class="label">操作</div>

              <el-button
                style="height: 100%"
                v-once-click
                color="#626aef"
                :icon="Search"
                @click="getRolesList"
              >
                查询
              </el-button>

              <div style="width: 10px"></div>

              <el-pagination
                v-model:current-page="pageNum"
                v-model:page-size="pageSize"
                :background="true"
                :total="roleTotal"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                layout="total, sizes, prev, pager, next"
                @size-change="handlePageSizeChange"
                @current-change="handlePageNumChange"
              />
            </div>
          </div>
        </template>

        <template #operationBar>
          <el-button
            v-once-click
            color="#626aef"
            plain
            size="small"
            @click="
              setUserRoles(UserDataSetTypeEnum.ADD, multipleSelectionItems)
            "
          >
            添加
          </el-button>

          <el-popconfirm
            title="确认重置当前用户角色？"
            placement="right"
            @confirm="
              setUserRoles(UserDataSetTypeEnum.REFRESH, multipleSelectionItems)
            "
          >
            <template #reference>
              <el-button v-once-click type="info" size="small">
                重置
              </el-button>
            </template>
          </el-popconfirm>
        </template>

        <template #table>
          <el-table
            ref="multipleTableRef"
            :data="queryRoleList"
            stripe
            size="small"
            style="width: 100%"
            max-height="300"
            @selection-change="handleSelectionChange"
            :headerCellStyle="tableHeaderCellStyle"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column property="enable" label="enable" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.enable === 1" type="danger">
                  禁用
                </el-tag>
                <el-tag v-if="scope.row.enable === 0" type="success">
                  启用
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column property="name" label="Name" sortable width="160">
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <div style="margin-right: 6px">{{ scope.row.name }}</div>
                  <el-icon
                    v-if="scope.row.isDefault == 0"
                    title="默认用户角色"
                    color="#eebe77"
                    size="17"
                  >
                    <InfoFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="realName" label="RealName" width="160" />
            <el-table-column label="Sort" min-width="400">
              <template #default="scope">
                {{
                  getDescriptionStr(
                    findParentValues(sortTree, scope.row?.sortId)
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column
              property="description"
              label="description"
              min-width="300"
            />
            <el-table-column label="operation" width="100" fixed="right">
              <template #default="scope">
                <!-- <el-tag  type="danger">
                  已添加
                </el-tag> -->
                <el-button
                  v-if="!hasRole(scope.row.id) && scope.row.isDefault != 0"
                  v-once-click
                  color="#626aef"
                  plain
                  size="small"
                  @click="setUserRoles(UserDataSetTypeEnum.ADD, [scope.row.id])"
                >
                  添加角色
                </el-button>

                <el-button
                  v-if="scope.row.isDefault == 0"
                  v-once-click
                  color="#67C23A"
                  plain
                  size="small"
                >
                  无需添加
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </TableCard>
    </div>

    <template #footer>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-button color="#626aef" size="large" @click="closeDialog">
          关闭弹窗
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { InfoFilled, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { storeToRefs } from 'pinia'
import { useSortTreeStore, useThemeStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'

import { getRolesListApi } from '@/request/api/roles'
import { getUserRolesDetailApi, setUserRolesApi } from '@/request/api/userRoles'
import { UserDataSetTypeEnum } from '@/type/enum'

import TableCard from '@/components/TableCard/TableCard.vue'

const props = defineProps({
  userInfo: { type: Object as () => UserInfoItf, default: {} },
  visible: { type: Boolean, default: false },
})

// 定义传递给父组件的方法
const emits = defineEmits(['closeDialogHandler'])
const closeDialog = () => emits('closeDialogHandler')

const { originData, sortTree } = storeToRefs(useSortTreeStore())
const { formattingSortData, getSortList, findParentValues, getDescriptionStr } =
  useSortTreeStore()

const { tableHeaderCellStyle } = useThemeStore()

const { openAlert } = useMessageAlertStore()

// 对话框显示时的回调
const openDialogHandler = () => {
  if (sortTree.value.length === 0) getSortList()

  const { id, nickname, account } = props.userInfo
  userId.value = id
  userName.value = nickname
  userAccount.value = account

  getRolesList()
  getUserRolesDetail()
}

const userId = ref<string>('')
const userName = ref<string>('')
const userAccount = ref<string>('')

// 经过筛选后的分类树形列表
const sortTypeTree = ref<SortTreeItf[]>([])
// 下拉框显示回调函数
const selectVisibleChangeHandler = (visible: boolean) => {
  if (!visible) return
  if (originData.value.length === 0) getSortList()
  sortTypeTree.value = formattingSortData(originData.value, null, 'role')
}

// 多选角色删除选项
const multipleDeleteItems = ref<string[]>([])
const deleteItemSelectionChange = (val: RoleItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleDeleteItems.value = ids
}

const userRoleList = ref<RoleItf[]>([])
// 获取用户角色详情
const getUserRolesDetail = async () => {
  const res = await getUserRolesDetailApi(userId.value)
  if (res.code !== 200) return openAlert.error(res.message)
  userRoleList.value = res.data.rolesList
}

// 判断用户是否已经拥有某个角色
const hasRole = (id: string): boolean => {
  if (!userRoleList.value || userRoleList.value.length === 0) return false
  return userRoleList.value.some((item) => item.id === id)
}

const roleTotal = ref<number>(0)
const pageNum = ref<number>(1)
const pageSize = ref<number>(20)
const handlePageNumChange = (val: number) => {
  pageNum.value = val
  getRolesList()
}
const handlePageSizeChange = (val: number) => {
  pageSize.value = val
  getRolesList()
}

// 角色分类id，包含所有上级分类id
const queryRoleSortId = ref<string[]>([])
// 查询角色名称
const queryRoleName = ref<string>('')

// 查询到的角色列表
const queryRoleList = ref<RoleItf[]>([])
// 获取角色列表
const getRolesList = async () => {
  let sortId = ''
  const q = queryRoleSortId.value
  if (q && q.length > 0) sortId = q[q.length - 1]

  const obj = {
    sortId: sortId,
    realName: queryRoleName.value,
  }
  const res = await getRolesListApi(pageNum.value, pageSize.value, obj)
  if (res.code !== 200) return openAlert.error(res.message)

  // ElMessage.success('查询角色成功')
  queryRoleList.value = res.data.records
  roleTotal.value = res.data.total
}

// 多选表格对象
const multipleTableRef = ref<any>()
// 多选权限选项
const multipleSelectionItems = ref<string[]>([])
const handleSelectionChange = (val: PermissionItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleSelectionItems.value = ids
}

// 为用户设置角色
const setUserRoles = async (
  type: UserDataSetTypeEnum,
  roleIdList: string[]
) => {
  const res = await setUserRolesApi(userId.value, type, roleIdList)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('设置角色成功')
  getUserRolesDetail()
  multipleTableRef.value!.clearSelection()
}
</script>

<style lang="less" scoped>
.label {
  font-size: 15px;
  font-weight: bold;
  color: #606266;
  padding: 0 14px;
  user-select: none;
}

.inputForm {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  > .inputItem {
    height: 40px;
    width: 500px;
    display: flex;
    align-items: center;
    margin-right: 15px;
    margin-bottom: 5px;
    // background-color: #cfcdcd21;

    > .label {
      min-width: 120px;
      height: 100%;
      font-size: 15px;
      font-weight: bold;
      color: #606266;
      user-select: none;
      background-color: #c8e0e4;
      display: flex;
      justify-content: center;
      align-items: center;
      padding-left: 5px;
      padding-right: 5px;
    }

    > .value {
      flex: 1;
      display: flex;
      height: 100%;
      border-radius: 4px;
      box-shadow: 0 0 1px 1px #bdbdbd8a;
    }
  }

  > .buttonItem {
    height: 40px;
    display: flex;
    align-items: center;
    padding-right: 10px;
    margin-right: 10px;
    margin-bottom: 5px;
    background-color: #cfcdcd21;

    > .label {
      min-width: 120px;
      height: 100%;
      font-size: 15px;
      font-weight: bold;
      color: #606266;
      user-select: none;
      background-color: #c8e0e4;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 10px;
      padding-left: 5px;
      padding-right: 5px;
    }
  }
}
</style>
